package com.huluobo.a2206koltindouyin.videos

import android.content.Intent
import android.util.Log
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.view.animation.AnimationUtils
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2206koltindouyin.R
import com.huluobo.a2206koltindouyin.adapter.CommentAdapter
import com.huluobo.a2206koltindouyin.adapter.MultiVideoAdapter
import com.huluobo.a2206koltindouyin.adapter.VideosAdapter
import com.huluobo.a2206koltindouyin.databinding.FragmentVideoBinding
import com.huluobo.a2206koltindouyin.live.LiveActivity
import com.huluobo.a2206koltindouyin.login.LoginActivity
import com.huluobo.base.bean.VideoBean
import com.huluobo.base.mvvm.BaseFragment
import com.huluobo.base.net.Const
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.umeng.socialize.ShareAction
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.parse
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
class VideoFragment : BaseFragment<FragmentVideoBinding, VideoViewModel>() {
    private lateinit var videosAdapter: MultiVideoAdapter
    private var currentPosition = 0
    private lateinit var player: StandardGSYVideoPlayer
    private lateinit var commentAdapter: CommentAdapter
    override fun initData() {
        vm.getAllVideos(2, 10)
        vm.getAllVideosSuccess.observe(this) {
            videosAdapter.data.clear()
            videosAdapter.data.addAll(it)
            videosAdapter.notifyDataSetChanged()
        }

        vm.likeVideoSuccess.observe(this) {
            ToastUtils.showLong(it)
            videosAdapter.data[currentPosition].dianzan = 1
            videosAdapter.notifyDataSetChanged()
        }

        vm.noLikeVideoSuccess.observe(this) {
            ToastUtils.showLong(it)
            videosAdapter.data[currentPosition].dianzan = 0
            videosAdapter.notifyDataSetChanged()
        }

        vm.followAuthSuccess.observe(this) {
            ToastUtils.showLong(it)
            videosAdapter.data[currentPosition].guanzhu = 1
            videosAdapter.notifyDataSetChanged()
        }

        vm.getCommentSuccess.observe(this) {
            commentAdapter.data.clear()
            commentAdapter.data.addAll(it)
            commentAdapter.notifyDataSetChanged()
        }

        vm.sendCommentSuccess.observe(this) {
            commentAdapter.data.addAll(0, it)
            commentAdapter.notifyDataSetChanged()
            val editText = videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_et) as EditText
            editText.text.clear()
        }

        vm.collectVideoSuccess.observe(this) {
            ToastUtils.showLong(it)
        }
    }

    override fun initView() {
        val linearLayoutManager = LinearLayoutManager(requireContext())
        binding.videosRv.layoutManager = linearLayoutManager
        videosAdapter = MultiVideoAdapter()
        binding.videosRv.adapter = videosAdapter
        val pagerSnapHelper = PagerSnapHelper()
        pagerSnapHelper.attachToRecyclerView(binding.videosRv)

        binding.videosRv.addOnScrollListener(object : OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                currentPosition = linearLayoutManager.findFirstVisibleItemPosition()
                player =
                    videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_player) as StandardGSYVideoPlayer
//                player.startPlayLogic()
            }
        })

        videosAdapter.addChildClickViewIds(
            R.id.item_videos_like_iv,
            R.id.item_videos_add_iv,
            R.id.item_videos_comment_iv,
            R.id.item_videos_close_iv,
            R.id.item_videos_comment_send_iv,
            R.id.item_videos_collect_iv,
            R.id.item_videos_share_iv,
            R.id.item_videos_live_cl,
            R.id.item_videos_full_cl
        )

        videosAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (SPUtils.getInstance().getString(Const.PARAM_TOKEN).isNullOrEmpty()) {
                val intent = Intent(requireContext(), LoginActivity::class.java)
                startActivity(intent)
            } else {
                val videoBean = videosAdapter.data[position]
                when (view.id) {
                    R.id.item_videos_like_iv -> likeVideo(videoBean)
                    R.id.item_videos_add_iv -> followAuth(videoBean)
                    R.id.item_videos_comment_iv -> openComment(videoBean)
                    R.id.item_videos_close_iv -> closeComment(videoBean)
                    R.id.item_videos_comment_send_iv -> sendComment(videoBean)
                    R.id.item_videos_collect_iv -> collectVideo(videoBean)
                    R.id.item_videos_share_iv -> shareVideo(videoBean)
                    R.id.item_videos_live_cl -> toLive(videoBean)
                    R.id.item_videos_full_cl -> fullScreen()
                }
            }
        }
    }

    private fun fullScreen() {
        player.isRotateViewAuto = true
        player.startWindowFullscreen(requireActivity(), false, false)
    }

    private fun toLive(videoBean: VideoBean) {
        val intent = Intent(requireContext(), LiveActivity::class.java)
        intent.putExtra(Const.PARAM_VIDEO_BEAN, videoBean)
        startActivity(intent)
    }

    private fun shareVideo(videoBean: VideoBean) {
        val umImage = UMImage(requireContext(), videoBean.videomainimg)
        umImage.compressStyle = UMImage.CompressStyle.SCALE

        val umWeb = UMWeb(videoBean.videopath)
        umWeb.title = videoBean.authname
        umWeb.setThumb(umImage)
        umWeb.description = videoBean.caption

        ShareAction(requireActivity())
            .withMedia(umWeb)
            .open()
    }

    private fun collectVideo(videoBean: VideoBean) {
        vm.collectVideo(videoBean)
    }

    private fun sendComment(videoBean: VideoBean) {
        val editText = videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_et) as EditText
        val sendMessage = editText.text.toString().trim()
        if (sendMessage.isNotEmpty()) {
            val map = mutableMapOf<String, Any>()
            map[Const.PARAM_VIDEO_ID] = videoBean.id
            map[Const.PARAM_MSG] = sendMessage
            val json = Gson().toJson(map)
            val body = RequestBody.create(Const.MEDIA_PARSE.toMediaTypeOrNull(), json)

            vm.sendComment(body)
        }


    }

    private fun closeComment(videoBean: VideoBean) {
        val commentLayout = videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_ll)
        val animOut = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_out)
        animOut.duration = 500
        animOut.interpolator = AccelerateInterpolator()
        animOut.setAnimationListener(object : AnimationListener {
            override fun onAnimationStart(animation: Animation?) {
            }

            override fun onAnimationEnd(animation: Animation?) {
                binding.videosRv.setIntercept(true)
                commentLayout?.visibility = View.GONE
            }

            override fun onAnimationRepeat(animation: Animation?) {
            }
        })
        commentLayout?.startAnimation(animOut)
    }

    private fun openComment(videoBean: VideoBean) {
        binding.videosRv.setIntercept(false)
        val commentLayout = videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_ll)
        commentLayout?.visibility = View.VISIBLE

        val commentRv: RecyclerView =
            videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_rv) as RecyclerView

        commentRv.layoutManager = LinearLayoutManager(requireContext())
        commentAdapter = CommentAdapter()
        commentRv.adapter = commentAdapter

        val animIn = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_in)
        animIn.duration = 500
        animIn.interpolator = AccelerateInterpolator()
        animIn.setAnimationListener(object : AnimationListener {
            override fun onAnimationStart(animation: Animation?) {
                vm.getComment(videoBean.id)
            }

            override fun onAnimationEnd(animation: Animation?) {
            }

            override fun onAnimationRepeat(animation: Animation?) {
            }
        })
        commentLayout?.startAnimation(animIn)
    }

    private fun followAuth(videoBean: VideoBean) {
        val map = mutableMapOf<String, String>()
        map[Const.PARAM_AUTHNAME] = videoBean.authname
        val json = Gson().toJson(map)
        val body = RequestBody.create(Const.MEDIA_PARSE.toMediaTypeOrNull(), json)
        vm.followAuth(body)
    }

    private fun likeVideo(videoBean: VideoBean) {
        if (videoBean.dianzan == 0) {
            vm.likeVideo(videoBean.id)
        } else {
            vm.noLikeVideo(videoBean.id)
        }
    }
}